package icu.groot.alan.filter;

import icu.groot.alan.entity.TokenEntity;
import icu.groot.alan.util.Token;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

@WebFilter(urlPatterns = {
        "/user/oneself.do",
        "/department/list.do",
        "/department/deleted.do",
        "/department/getall.do",
        "/department/add.do",
        "/user/list.do",
        "/user/add.do",
        "/user/deleted.do",
        "/user/_update.do",
        "/user/update.do",
        "/task/list.do",
        "/announce/announce.do",
        "/report/add.do",
        "/report/export/excel.export"
})
public class FilterB_Token implements Filter {
    Logger logger = Logger.getLogger("icu.groot.alan.filter.TokenFilter");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //得到请求中的token
        String token = "";
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        Cookie cs[] = req.getCookies();
        if (cs != null) {
            for (Cookie c : cs) {
                if (c.getName().equals("token")) {
                    token = c.getValue();
                }
            }
        }
        //校验token
        if (token == null || token.equals("")){
            logger.info("token校验失败");
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }else {
            TokenEntity tokenEntity = Token.verify(token);
            if (tokenEntity == null) {
                logger.info("token校验失败");
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            }else {
                logger.info("token校验通过: " + tokenEntity.toString());
                //将token中的信息放入域中
                servletRequest.setAttribute("tokenEntity", tokenEntity);
                //进入下一个过滤器
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
